<?php

namespace App\Jobs;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class AddUserApplesJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	public $user;
	
	public function __construct(User $user)
	{
		$this->user = $user;
	}
	
	public function handle()
	{
		$user = $this->user;

		if($user->rewarded_at > 0){
            $time = time()-intval($user->rewarded_at);
        }else{

          return false;
        }

        $ownApples = $user->ownOneSeconds()->multipliedBy($time);
        account_apples($user)->plusOwnTreeProduceApples($ownApples);
        $res = $user->myDownOneChildren()->get();
        /*foreach($res as $v){
           $v->dividendChildApples();
        }*/
        if($res && $user->oneLevelTeamSeconds()->isGreaterThan(0)){
            $ownApples = $user->oneLevelTeamSeconds()->multipliedBy($time);
            account_apples($user)->plusTreeProduceApples($ownApples,1);

        }

        for($i=2;$i<=2;$i++){

            $hasValidUser = $user->myTeam()->where('relation_users.team_level',$i)->exists();
           
            if($hasValidUser && $user->allowedPart($i)){
                if($user->moreLevelTeamSeconds($i)->isGreaterThan(0)){

                     account_apples($user)->plusTreeProduceApples($user->moreLevelTeamSeconds($i)->multipliedBy($time),$i);
                }

            }

        }

        $user->update(['rewarded_at'=>time()]);
		
	}
}
